package com.fysports.web.kit.commons;

import com.jfinal.log.Log;
import com.fysports.framework.exception.FrameException;
import com.fysports.framework.kit.security.IDEASecurityKit;
import com.fysports.web.config.AppConst;
import com.fysports.web.model.system.SystemUser;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;


/**
 * Created by konbluesky
 * Date : 14-8-2 上午10:43
 * Project : JdmData_WebServer
 */
public class CookiesKit {
    private static Log logger = Log.getLog(CookiesKit.class);
    public final static String COOKIES_AUTHMARK = "authmark";
    public final static String COOKIES_MOBILE_AUTHMARK = "m_authmark";
    public final static String COOKIES_LOCK = "lock";


    /**
     * 生成cookie令牌
     *
     * @param request
     * @param user
     * @return
     */
    public static String getCookieAuthToken(HttpServletRequest request, SystemUser user) {
        String userIds = user.getStr("uuid");
        String username = user.getStr("name");
        //        String userIds = "ABCDEFGHIJKLMN";
        String ips = IPAddressKit.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        /*过期时间 当前时间 +1 天 /单位:秒*/
        long date = DateTimeKit.getDateByTime() + DateTimeKit.time_day * 1000;

        StringBuffer token = new StringBuffer();// 时间戳#USERID#USER_IP#USER_AGENT

        token.append(AppConst.APPNAME).append(".#.").append(date).append(".#.").append(userIds).append(".#.")
                .append(username).append(".#.").append(ips).append(".#.").append(userAgent).append(".#.")
                .append(user.getStr("bigicon"));
        String authToken = token.toString();
        byte[] authTokenByte = null;
        try {
            authTokenByte = authToken.getBytes(StringKit.encoding);
        }
        catch (UnsupportedEncodingException e) {
            logger.error(e.getLocalizedMessage(),e);
            throw new FrameException(e);
        }
        // 加密
        byte[] securityByte = null;
        try {
            securityByte = IDEASecurityKit.encrypt(authTokenByte);
        }
        catch (Exception e) {
            logger.error(e.getLocalizedMessage(),e);
            throw new FrameException(e);
        }
        String securityCookie = StringKit.encodeBase64(securityByte);

        return securityCookie;
    }


    /**
     * 解密cookie令牌
     *
     * @param encodeCookie
     * @return //<br/>
     * arr[0]：应用名称<br/>
     * arr[1]：时间戳<br/>
     * arr[2]：USERID<br/>
     * arr[3]：USER_NAME<br/>
     * arr[4]：USER_IP<br/>
     * arr[5]：USER_AGENT<br/>
     * arr[6]：USER_ICON
     */
    public static CookieVO decodeCookieAuthToken(String encodeCookie) {
        // 解密

        byte[] securityByte = StringKit.decodeBase64(encodeCookie);
        byte[] dataByte = null;
        try {
            dataByte = IDEASecurityKit.decrypt(securityByte);
        }
        catch (Exception e) {
            logger.error(e.getLocalizedMessage(),e);
            throw new FrameException(e);
        }
        String data = new String(dataByte);
        CookieVO cvo = new CookieVO(data);
        return cvo;
    }


    private static String getSystemUserUUID(String cookie) {
        if (cookie == null || cookie.length() == 0) {
            return "";
        }
        return decodeCookieAuthToken(cookie).getUserid();
    }


    public static String getSystemUserUUID(HttpServletRequest request) {
        Cookie c = getCookie(request, COOKIES_AUTHMARK);
        return getSystemUserUUID(c != null ? c.getValue() : "");
    }


    public static SystemUser getSystemUser(HttpServletRequest request) {
        String useruuid = getSystemUserUUID(request);
        return SystemUser.dao.findById(useruuid);
    }


    public static Cookie getCookie(HttpServletRequest request, String key) {
        Cookie[] ck = request.getCookies();
        Cookie result = null;
        if (ck != null && ck.length > 0) {
            for (Cookie c : ck) {
                if (c.getName().equals(key)) {
                    result = c;
                }
            }
        }
        return result;
    }
    public static class CookieVO {
        /**
         * arr[0]：应用名称<br/>
         * arr[1]：时间戳<br/>
         * arr[2]：USERID<br/>
         * arr[3]：USER_NAME<br/>
         * arr[4]：USER_IP<br/>
         * arr[5]：USER_AGENT<br/>
         * arr[6]：USER_ICON
         */
        private String appname;
        private String date;
        private String userid;
        private String username;
        private String userip;
        private String useragent;
        private String userimg;


        public CookieVO(String val) {
            String[] dataArr = val.split(".#.");
            if (StringKit.notBlank(dataArr) && dataArr.length == 7) {
                this.appname = dataArr[0];
                this.date = dataArr[1];
                this.userid = dataArr[2];
                this.username = dataArr[3];
                this.userip = dataArr[4];
                this.useragent = dataArr[5];
                this.userimg = dataArr[6];
            }
            else {
                this.appname = this.date =
                        this.userid = this.userip = this.username = this.useragent = this.userimg = "";
            }
        }


        public String getDate() {
            return date;
        }


        public String getAppname() {
            return appname;
        }


        public String getUserid() {
            return userid;
        }


        public String getUserip() {
            return userip;
        }


        public String getUseragent() {
            return useragent;
        }


        public String getUsername() {
            return username;
        }


        public String getUserimg() {
            return userimg;
        }
    }

}
